<template>
  <div class="carousel-manager">
    <div class="section-header">
      <h3>{{ title }}</h3>
      <el-button type="primary" size="small" @click="addCarouselItem">
        <el-icon><Plus /></el-icon>
        添加轮播图
      </el-button>
    </div>

    <el-table :data="carouselData" border stripe v-loading="loading">
      <el-table-column prop="title" label="标题" width="200" />
      <!-- <el-table-column prop="subtitle" label="副标题" width="200" /> -->
      <el-table-column prop="description" label="描述" width="250" />
      <el-table-column label="图片" width="120">
        <template #default="{ row }">
          <el-image
            :src="row.image"
            :preview-src-list="[row.image]"
            fit="cover"
            style="width: 80px; height: 50px; border-radius: 4px"
          />
        </template>
      </el-table-column>
      <el-table-column prop="buttonText" label="按钮文字" width="120" />
      <el-table-column prop="action" label="跳转动作" width="120" />
      <el-table-column prop="sort" label="排序" width="80" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 'active' ? 'success' : 'info'">
            {{ row.status === "active" ? "启用" : "禁用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row, $index }">
          <el-button type="primary" size="small" @click="editCarouselItem(row)">
            编辑
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="deleteCarouselItem($index)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑对话框 -->
    <el-dialog
      :title="editDialogTitle"
      v-model="editDialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="editForm"
        label-width="100px"
        :rules="formRules"
        ref="editFormRef"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="editForm.title" placeholder="请输入标题" />
        </el-form-item>

        <!-- <el-form-item label="副标题" prop="subtitle">
          <el-input v-model="editForm.subtitle" placeholder="请输入副标题" />
        </el-form-item> -->

        <el-form-item label="描述" prop="description">
          <el-input
            v-model="editForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入描述"
          />
        </el-form-item>

        <el-form-item label="图片" prop="image">
          <div class="image-upload-container">
            <el-upload
              class="image-uploader"
              :action="uploadAction"
              :headers="uploadHeaders"
              :data="{ type: moduleType }"
              :show-file-list="false"
              :on-success="handleImageSuccess"
              :before-upload="beforeImageUpload"
              accept="image/*"
            >
              <img
                v-if="editForm.image"
                :src="editForm.image"
                class="uploaded-image"
              />
              <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <el-input
              v-model="editForm.image"
              placeholder="或直接输入图片URL"
              style="margin-top: 10px"
            />
          </div>
        </el-form-item>

        <el-form-item label="按钮文字" prop="buttonText">
          <el-input
            v-model="editForm.buttonText"
            placeholder="请输入按钮文字"
          />
        </el-form-item>

        <el-form-item label="跳转动作" prop="action">
          <el-input v-model="editForm.action" placeholder="请输入跳转动作" />
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="editForm.sort" :min="1" :max="999" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="editForm.status">
            <el-radio value="active">启用</el-radio>
            <el-radio value="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEditForm" :loading="saving"
          >保存</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { homepageApi } from "@/api/admin";
import config from "@/config";

// Props
const props = defineProps({
  title: {
    type: String,
    default: "轮播图管理",
  },
  moduleType: {
    type: String,
    required: true,
  },
});

// 响应式数据
const loading = ref(false);
const saving = ref(false);
const carouselData = ref([]);
const editDialogVisible = ref(false);
const editDialogTitle = ref("");
const editForm = reactive({});
const editFormRef = ref();

// 图片上传相关
const apiConfig = config.getApiConfig();
const uploadAction = ref(`${apiConfig.baseURL}/api/upload/image`);
const uploadHeaders = ref({
  token: localStorage.getItem("adminToken") || "",
});

// 表单验证规则
const formRules = {
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
  image: [{ required: true, message: "请上传图片", trigger: "blur" }],
};

// 加载轮播图数据
const loadCarouselData = async () => {
  loading.value = true;
  try {
    const response = await homepageApi.getContentByType(
      `carousel_${props.moduleType}`
    );
    if (response && response.code === "200" && response.data) {
      carouselData.value = response.data
        .map((item) => {
          const content =
            typeof item.content === "string"
              ? JSON.parse(item.content)
              : item.content;
          return {
            id: item.id,
            title: item.title,
            subtitle: item.subtitle || "",
            description: content.description || "",
            image: item.imageUrl || content.image || "",
            buttonText: content.buttonText || "",
            action: content.action || "",
            sort: item.sortOrder || 1,
            status: item.status || "active",
          };
        })
        .sort((a, b) => a.sort - b.sort);
    } else {
      carouselData.value = [];
    }
  } catch (error) {
    console.error("加载轮播图数据失败:", error);
    ElMessage.error("加载数据失败");
    carouselData.value = [];
  } finally {
    loading.value = false;
  }
};

// 添加轮播图
const addCarouselItem = () => {
  editDialogTitle.value = "添加轮播图";
  Object.keys(editForm).forEach((key) => delete editForm[key]);
  Object.assign(editForm, {
    title: "",
    subtitle: "",
    description: "",
    image: "",
    buttonText: "",
    action: "",
    sort: carouselData.value.length + 1,
    status: "active",
  });
  editDialogVisible.value = true;
};

// 编辑轮播图
const editCarouselItem = (row) => {
  editDialogTitle.value = "编辑轮播图";
  Object.assign(editForm, { ...row });
  editDialogVisible.value = true;
};

// 删除轮播图
const deleteCarouselItem = async (index) => {
  try {
    await ElMessageBox.confirm("确定要删除这个轮播图吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const item = carouselData.value[index];
    if (item.id) {
      // 如果有ID，调用API删除
      const response = await homepageApi.deleteContent(item.id);
      if (response && response.code === "200") {
        carouselData.value.splice(index, 1);
        ElMessage.success("删除成功");
      } else {
        ElMessage.error("删除失败");
      }
    } else {
      // 如果没有ID，直接删除
      carouselData.value.splice(index, 1);
      ElMessage.success("删除成功");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除轮播图失败:", error);
      ElMessage.error("删除失败");
    }
  }
};

// 保存编辑表单
const saveEditForm = async () => {
  try {
    await editFormRef.value.validate();
    saving.value = true;

    const formData = {
      contentType: `carousel_${props.moduleType}`,
      title: editForm.title,
      subtitle: editForm.subtitle || "",
      imageUrl: editForm.image,
      content: JSON.stringify({
        description: editForm.description || "",
        buttonText: editForm.buttonText || "",
        action: editForm.action || "",
      }),
      sortOrder: editForm.sort,
      status: editForm.status,
    };

    if (editForm.id) {
      // 更新现有数据
      formData.id = editForm.id;
      await homepageApi.updateContent(formData);
    } else {
      // 创建新数据
      await homepageApi.addContent(formData);
    }

    ElMessage.success("保存成功");
    editDialogVisible.value = false;
    await loadCarouselData();
  } catch (error) {
    if (error !== false) {
      // 表单验证失败时error为false
      console.error("保存失败:", error);
      ElMessage.error("保存失败");
    }
  } finally {
    saving.value = false;
  }
};

// 图片上传成功处理
const handleImageSuccess = (response) => {
  if (response && response.code === "200") {
    editForm.image = response.data.url;
    ElMessage.success("图片上传成功!");
  } else {
    ElMessage.error("图片上传失败!");
  }
};

// 图片上传前验证
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith("image/");
  const isLt2M = file.size / 1024 / 1024 < 15;

  if (!isImage) {
    ElMessage.error("只能上传图片文件!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过 15MB!");
    return false;
  }
  return true;
};

// 监听模块类型变化，重新加载数据
watch(
  () => props.moduleType,
  () => {
    loadCarouselData();
  },
  { immediate: true }
);

// 组件挂载时加载数据
onMounted(() => {
  loadCarouselData();
});
</script>

<style scoped>
.carousel-manager {
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-header h3 {
  margin: 0;
  color: #2c3e50;
}

.image-upload-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.image-uploader:hover {
  border-color: #409eff;
}

.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 80px;
  line-height: 80px;
  text-align: center;
}

.uploaded-image {
  width: 120px;
  height: 80px;
  object-fit: cover;
  display: block;
}
</style>
